'''
Created on Mar 18, 2011

'''

from google.appengine.ext import db
from geoserv import Geometry, commandRequest
import logging


import userio
from locator import Location
"""
def singleCommand(inputCommand,userinfo):
    values = {
              'atItem': thereYet(userinfo),
              'drawingCorner': settingCorner(userinfo),
              'whereIsItem': getItemLoc(userinfo)
              }
    return values.get(inputCommand, defaultFunction())
"""
"""
def input(inputCommand,userinfo):
    values = {
              'atItem': thereYet(userinfo),
              'drawingCorner': settingCorner(userinfo),
              'whereIsItem': getItemLoc(userinfo),
              'setTreasure': settingTreasure(userinfo),
              'startNewGame': startingNewGame(userinfo),
              'echo': distanceBetween(userinfo)
              }
    return values.get(inputCommand, defaultFunction())
"""
def input(inputCommand,userinfo):
    logging.info("class input got %r for inputComand", inputCommand)
    if inputCommand=='atItem':
        return thereYet(userinfo)
    elif inputCommand=='drawingCorner':
        return settingCorner(userinfo)
    elif inputCommand=='whereIsItem':
        return getItemLoc(userinfo)
    elif inputCommand=='setTreasure':
        return settingTreasure(userinfo)
    elif inputCommand=='startNewGame':
        return startingNewGame(userinfo)
    elif inputCommand=='echo':
        return distanceBetween(userinfo)
    elif inputCommand=='cNd':
        gamesession = userio.GameSession.get_by_key_name(userinfo.playerGameID)
        gamesession.teamAHasXToPlace = 1
        gamesession.teamBHasXToPlace = 1
        gamesession.put()
        return ''
    elif inputCommand=='showmethemoney':
        gamesession = userio.GameSession.get_by_key_name(userinfo.playerGameID)
        if userinfo.team=='Webfest A':
            gamesession.teamAscore = gamesession.teamAscore +1
        else:
            gamesession.teamBscore = gamesession.teamBscore +1
        return ''
    else:
        return defaultFunction()

def distanceBetween(userinfo):
    """
    if there is an item for the user to be near, give the distance
    if there is no item for the user to be near, give null
    """
    query = Geometry.all()
    query.filter('type = ', 'point')
    query.filter('name = ', userinfo.team)
    query.order("-dateModified")
    
    locations = []
    for geometry in query.fetch(1):
      location = Location(geometry)
      location.set_distance(float(userinfo.loc_lat),float(userinfo.loc_long))
      locations.append(location)
    if len(locations) == 0:
        logging.info("There are no items in DB to compare distance to, returning null")
        return "null"
    #up to here gets me locations[0].distance, and returns null if nothing is found in DB
    gamesession = userio.GameSession.get_by_key_name(userinfo.playerGameID) 
    if userinfo.team=='Webfest A':
            if gamesession.teamBHasXToPlace == 0:
                response = str(locations[0].distance)
                logging.info("distanceBetween is responding with %r", response)
                return response
            else:
                logging.info("Team B has an item to place, thus returning null for distanceBetween")
                return "null"
    elif userinfo.team=='Webfest B':
            if gamesession.teamAHasXToPlace == 0:
                response = str(locations[0].distance)
                logging.info("distanceBetween is responding with %r", response)
                return response
            else:
                logging.info("Team A has an item to place, thus returning null for distanceBetween")
                return "null"
    else:
        logging.info("Team: %r , does not match A or B, returning null", userinfo.team)
        return "null"

def thereYet(userinfo):

    query = Geometry.all()
    query.filter('type = ', 'point')
    query.filter('name = ', userinfo.team)
    query.order("-dateModified")
    
    locations = []
    for geometry in query.fetch(1):
      location = Location(geometry)
      location.set_distance(float(userinfo.loc_lat),float(userinfo.loc_long))
      locations.append(location)
    if len(locations) == 0:
        return "1"
    elif float(userinfo.gpsAccuracy)>35:
        logging.info("GPS Accuracy is too low to check if there yet. Accuracy is: %r", userinfo.gpsAccuracy)
        return "0"
    elif locations[0].distance<=float(userinfo.gpsAccuracy):
        gamesession = userio.GameSession.get_by_key_name(userinfo.playerGameID)
        if userinfo.team=='Webfest A':
            if gamesession.teamBHasXToPlace == 0:
                gamesession.teamAHasXToPlace = 1
                gamesession.teamBHasXToPlace = 1
                gamesession.teamAscore = gamesession.teamAscore+1
            else:
                logging.info("The other team has not placed an item (teamBHasXToPlace is not 0). Therfore, I am at Item, but not doing anything")
                return "0"
        else:
            if gamesession.teamAHasXToPlace == 0:
                gamesession.teamAHasXToPlace = 1
                gamesession.teamBHasXToPlace = 1
                gamesession.teamBscore = gamesession.teamBscore+1
            else:
                logging.info("The other team has not placed an item (teamAHasXToPlace is not 0). Therfore, I am at Item, but not doing anything")
                return "0"
        gamesession.put()
        return "1"
        # + str(locations[0].distance) + '<=' + str(float(userinfo.Accuracy))
    else:
        logging.info("user is not at item, thus atItem is returning 0")
        return "0"
        # + str(locations[0].distance) + '>' + str(float(userinfo.Accuracy))


def settingCorner(userinfo):

    dict = {'name': userinfo.team + " Box", 'type': 'poly', 'description': "Created by users ingame"}
    query=Geometry.all()
    query.filter('type = ', 'poly')
    query.filter('name = ', userinfo.team + " Box")
    query.order("-dateModified")
    geometry=query.get()
    if geometry==None:
        dict['operation']='add'
    else:
        dict['operation']='edit'
        dict['key'] = geometry.key()
    dict['lat']=float(userinfo.loc_lat)
    dict['lng']=float(userinfo.loc_long)
    
    commandRequest(dict)
    if geometry==None:
        return 1
    else:
        return str(len(geometry.coordinates)+1)

def settingTreasure(userinfo):
    gamesession = userio.GameSession.get_by_key_name(userinfo.playerGameID)
    if float(userinfo.gpsAccuracy)>65:
        logging.info("GPS Accuracy is too low to place item. Accuracy is: %r", userinfo.gpsAccuracy)
        return "0"
    elif userinfo.team=='Webfest A':
        setTeam = 'Webfest B'
        if gamesession.teamAHasXToPlace == 1:
                dict = {'name': setTeam + "", 'type': 'point', 'description': "Created by users ingame as treasure"}
                dict['operation']='add'
                dict['lat']=float(userinfo.loc_lat)
                dict['lng']=float(userinfo.loc_long)
                commandRequest(dict)
                gamesession.teamAHasXToPlace = 0
                gamesession.put()
                return "1"
        else:
            logging.info("Team A has no items to place")
            return "0"
    elif userinfo.team=='Webfest B':
        setTeam = 'Webfest A'
        if gamesession.teamBHasXToPlace == 1:
                dict = {'name': setTeam + "", 'type': 'point', 'description': "Created by users ingame as treasure"}
                dict['operation']='add'
                dict['lat']=float(userinfo.loc_lat)
                dict['lng']=float(userinfo.loc_long)
                commandRequest(dict)   
                gamesession.teamBHasXToPlace = 0
                gamesession.put()
                return "1"    
        else:
            logging.info("Team B has no items to place")
            return "0" 
    else:
        logging.info("user has invalid team")
        return "0"

def getItemLoc(userinfo):
    logging.info("user's team is: %r", userinfo.team)
    query = Geometry.all()
    query.filter('type = ', 'point')
    query.filter('name = ', userinfo.team)
    query.order("-dateModified")
    geometry=query.get()
    return str(geometry.coordinates[0].lat) + ' ' + str(geometry.coordinates[0].lon)

def startingNewGame(userinfo):
    gamesession = userio.GameSession.get_by_key_name(userinfo.playerGameID)
    if gamesession.teamAscore >= 5 or gamesession.teamBscore >= 5:
        gamesession.teamAscore = 0
        gamesession.teamBscore = 0
        gamesession.teamAHasXToPlace = 1
        gamesession.teamBHasXToPlace = 1
        gamesession.put()
        return "1"
    else:
        return "0"


def defaultFunction():
    logging.info("Called invalid command")
    return 'Error! No such command'

    